package com.crocodileq.interceptor;


import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.crocodileq.dto.UserDTO;
import com.crocodileq.utils.UserHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/***
 * @Author 鳄鱼杆
 * @Date 2025/9/10 15:03
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1、判断用户是否存在
        UserDTO user = UserHolder.getUser();
        //2、不存在，返回401
        if(ObjectUtils.isNull(user)){
            response.setStatus(401);
            return false;
        }

        //3、存在，放行

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //threadLocal中移除用户信息
        UserHolder.removeUser();
    }
}
